package com.zw.blog.service.impl;

import com.zw.blog.dao.TagRepository;
import com.zw.blog.exception.NotFoundException;
import com.zw.blog.po.Tag;
import com.zw.blog.service.TagService;
import com.zw.blog.util.MyBeanUtils;
import com.zw.blog.util.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.util.ArrayList;
import java.util.List;
import java.lang.Long;


@Service
public class TagServiceImpl implements TagService {

    @Autowired
    public TagServiceImpl(TagRepository tagRepository) {
        this.tagRepository = tagRepository;
    }
    private TagRepository tagRepository;

    @Transactional //放到事务里面
    @Override
    public Tag saveTag(Tag tag) {
        return tagRepository.save(tag);
    }

    @Transactional
    @Override
    public Tag getTag(Long id) {
        return tagRepository.getOne(id);
    }

    @Transactional
    @Override
    public Tag getTagByName(String name) {
        return tagRepository.findTagByName(name);
    }

    @Transactional
    @Override
    public Page<Tag> listTag(Pageable pageable) {
        return tagRepository.findAll(pageable); //???Pageable是啥
    }

    @Override
    public List<Tag> listTag() {
        return tagRepository.findAll();
    }


    private List<Long> convertToList(String ids) {
        List<Long> list = new ArrayList<>();
        if (ids != null && ids.length() != 0) {
            String[] idArray = ids.split(",");
            for (String s : idArray) {
                if (!StringUtils.isNumeric(s)) {
                    Tag t = new Tag();
                    t.setName(s);
                    tagRepository.save(t);
                    list.add(t.getId());
                } else {
                    list.add(Long.parseLong(s));
                }
            }
        }
        return list;
    }
    @Override
    public List<Tag> listTag(String ids) { //1, 2, 3
        return tagRepository.findAllById(convertToList(ids));
    }

    @Override
    public List<Tag> listTagTop(Integer size) {
        Sort sort = Sort.by(Sort.Direction.DESC, "blogs.size");
        Pageable pageable = PageRequest.of(0, size, sort);
        return tagRepository.findTop(pageable);
    }

    @Transactional
    @Override
    public Tag updateTag(Long id, Tag tag) {
        Tag t = tagRepository.findTagById(id);
        if (t == null) throw new NotFoundException("没有该标签！");
        BeanUtils.copyProperties(tag, t);
        return tagRepository.save(t);
    }

    @Transactional
    @Override
    public void deleteTag(Long id) {
        tagRepository.deleteById(id);
    }
}
